package com.mainbo.modular.system.controller.user;

import cn.stylefeng.roses.core.base.controller.BaseController;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mainbo.core.common.constant.ApolloConstants;
import com.mainbo.core.common.constant.ConfigUtils;
import com.mainbo.core.shiro.SessionKey;
import com.mainbo.core.shiro.ShiroKit;
import com.mainbo.core.util.Result;
import com.mainbo.jms.MessageTypes;
import com.mainbo.modular.excel.ExcelBatchService;
import com.mainbo.modular.jms.JmsService;
import com.mainbo.modular.jms.model.PeopleStudentMessageVo;
import com.mainbo.modular.jms.model.PeopleStudentVo;
import com.mainbo.modular.system.dao.PtPeopleStudentMapper;
import com.mainbo.modular.system.dao.PtStudentMapper;
import com.mainbo.modular.system.model.*;
import com.mainbo.modular.system.model.meta.*;
import com.mainbo.modular.system.model.meta.vo.Meta;
import com.mainbo.modular.system.service.IPtAccountService;
import com.mainbo.modular.system.service.IPtClassUserService;
import com.mainbo.modular.system.service.IPtOrgService;
import com.mainbo.modular.system.service.PeopleService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import com.mainbo.core.log.LogObjectHolder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * 学生家长
 *
 * @author moshang
 * @Date 2020-03-12 16:04:22
 */
@Controller
@RequestMapping("/ptPeople")
public class PtPeopleController extends BaseController {

    private static final Logger logger= LoggerFactory.getLogger(PtPeopleController.class);
    private String PREFIX = "/system/ptPeople/";

    @Resource
    private PeopleService ptPeopleService;
    @Resource
    private IPtOrgService orgService;
    @Resource
    private PtPeopleStudentMapper  ptPeopleStudentMapper;
    @Resource
    private IPtClassUserService classUserService;
    @Resource
    private PtStudentMapper studentMapper;
    @Resource
    private JmsService jmsService;
    @Resource
    private IPtAccountService accountService;
    @Resource(name = "batchExportUserServiceImpl")
    private ExcelBatchService batchExportUserService;

    /**
     * 跳转到首页
     */
    @RequestMapping("")
    public String index(Model model) {
        PtOrg org = ShiroKit.getSessionAttr(SessionKey.CURRENT_ORG);
        if ((org == null)) {

            model.addAttribute("orgId","0");
            return PREFIX + "ptPeople_org.html";
        }
        // 学校的学段集合
        List<Meta> phaseList = MetaUtils.getOrgTypeProvider().listAllPhase(org.getSchoolings());
        // 学校的学段-年级map
        model.addAttribute("phaseList", phaseList);
        model.addAttribute("org",org);
        return PREFIX + "ptPeople_list.html";
    }

    /**
     * 跳转到添加
     */
    @RequestMapping("/ptPeople_add")
    public String ptPeopleAdd(Model model,String orgId) {
        PtOrg org=orgService.selectById(orgId);
        model.addAttribute("org",org);
        model.addAttribute("uploadUrl", ApolloConstants.readUploadUrl());
        model.addAttribute("GBSex", GBSex.values());
        model.addAttribute("GBNation", GBNation.values());
        model.addAttribute("GBPapersType", GBPapersType.values());
        model.addAttribute("uploadUrl", ApolloConstants.readUploadUrl());
        // 学校的学段集合
        List<Meta> phaseList = MetaUtils.getOrgTypeProvider().listAllPhase(org.getSchoolings());
        // 学校的学段
        model.addAttribute("phaseList", phaseList);
        return PREFIX + "ptPeople_add.html";
    }
    /**
     * 跳转到修改
     */
    @RequestMapping("/ptPeople_update/{peopleId}")
    public String ptPeopleUpdate(Model model,@PathVariable String peopleId) {
        People people=ptPeopleService.selectById(peopleId);
        model.addAttribute("people",people);
        model.addAttribute("uploadUrl", ApolloConstants.readUploadUrl());
        model.addAttribute("storageUrl", ApolloConstants.readStorageUrl());
        model.addAttribute("GBSex", GBSex.values());
        model.addAttribute("GBNation", GBNation.values());
        model.addAttribute("GBPapersType", GBPapersType.values());
        model.addAttribute("uploadUrl", ApolloConstants.readUploadUrl());
        return PREFIX + "ptPeople_edit.html";
    }
    /**
     * 根据学段获取年级
     *
     * @param orgId
     *          机构id
     * @param phaseId
     *          学段id
     * @return 返回
     */
    @ResponseBody
    @RequestMapping("/getGradeByPhaseId")
    public Object getGradeByPhaseId(String orgId, Integer phaseId) {
        PtOrg org = orgService.selectById(orgId);
        Map<Integer, List<Meta>> phaseGradeMap = MetaUtils.getOrgTypeProvider().listPhaseXzGradeMap(org.getSchoolings());
        List<Meta> list = phaseGradeMap.get(phaseId);
        return list;
    }

    /**
     * 根据年级获取班级信息
     *
     * @param classInfo
     *          班级信息
     * @return 返回
     */
    @ResponseBody
    @RequestMapping("/getClassByGradeId")
    public Object getClassByGradeId(PtClass classInfo) {
        classInfo.setSchoolYear(MetaUtils.getSchoolYearProvider().getCurrentSchoolYear(classInfo.getOrgId()));
        EntityWrapper<PtClass> entityWrapper=new EntityWrapper<>();
        entityWrapper.eq("org_id",classInfo.getOrgId());
        entityWrapper.eq("phase_id",classInfo.getPhaseId());
        entityWrapper.eq("grade_id",classInfo.getGradeId());
        List<PtClass> findAll = classInfo.selectList(entityWrapper);
        return findAll;
    }
    /**
     * 跳转到查看
     */
    @RequestMapping("/ptPeople_showInfo/{id}")
    public String ptStudentShowInfo(@PathVariable String id, Model model) {
        model.addAttribute("uploadUrl", ApolloConstants.readUploadUrl());
        model.addAttribute("storageUrl", ApolloConstants.readStorageUrl());
        People people=ptPeopleService.selectById(id);
        PtAccount account=accountService.selectById(id);
        people.setAccountName(account.getAccount());
        model.addAttribute("item",people);
        model.addAttribute("sex", GBSex.forCname(people.getSex()));
        if (people.getNationCode()==null){
            model.addAttribute("GBNation","");
        }else {
            model.addAttribute("GBNation", GBNation.forCname(people.getNationCode()));
        }
        if (people.getPapersType()==null){
            model.addAttribute("GBPapersType","");
        }else {
            model.addAttribute("GBPapersType", GBPapersType.forCname(people.getPapersType()));
        }
        LogObjectHolder.me().set(people);
        return PREFIX + "ptPeople_view.html";
    }
    /**
     * 获取列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(UserSearchModel um) {

        if (StringUtils.isBlank(um.getOrgId())){
            return new ArrayList<Student>();
        }
        return ptPeopleService.findPeopleByCondition(um);
    }

    /**
     * 保存家长数据
     *
     * @param people
     *          用户
     * @param peopleStu
     *          家长学生
     * @return 返回
     */
    @RequestMapping(value = "/saveParents", method = RequestMethod.POST)
    @ResponseBody
    public Result saveParents(People people, PtPeopleStudent peopleStu) {
        Result result = new Result();
        try {
            People save = ptPeopleService.saveParents(people);
            peopleStu.setPeopleId(save.getId());
            PtPeopleStudent getOne = ptPeopleStudentMapper.selectOne(peopleStu);
            if (getOne == null) {
                if (StringUtils.isNotBlank(peopleStu.getStudentId())){
                    Student student=studentMapper.selectById(peopleStu.getStudentId());
                    if (student!=null){
                        peopleStu.setStudentName(student.getName());
                    }
                }
                peopleStu.setCrtDttm(new Date());
                ptPeopleStudentMapper.insert(peopleStu);
               // LoggerUtils.insertLogger(LoggerModule.YHGL, "用户管理——添加家长子女关系，家长用户ID：{}", save.getId());
                this.sendMessage(MessageTypes.PEOPLE_STUDENT_ADD, peopleStu);
            }
            result.setCode(Result.SUCCESS);
            result.setMsg("操作成功");
            logger.info("保存成功");
        } catch (Exception e) {
            logger.info("保存失败", e);
            result.setCode(Result.FAIL);
            result.setMsg("操作失败");
        }
        return result;
    }

    /**
     * @param type
     *          类型
     * @param ps
     *          学生家长
     */
    public void sendMessage(MessageTypes type, PtPeopleStudent ps) {
        try {
            PeopleStudentMessageVo vo = new PeopleStudentMessageVo();
            vo.setMessageType(type.name());
            PeopleStudentVo peopleStudentVo = new PeopleStudentVo();
            BeanUtils.copyProperties(ps, peopleStudentVo);
            vo.setPeopleStudentVo(peopleStudentVo);
            jmsService.sendMessage(vo);
        } catch (Exception e) {
            logger.error("发送消息失败，消息类型{}", type.name(), e);
        }

    }
    @RequestMapping(value = "/delete/{peopleId}")
    @ResponseBody
    public Result delete(@PathVariable String peopleId, Boolean deleted) {
        Result result = new Result();
        try {
            accountService.deleteUser(peopleId, deleted);
            result.setMsg("操作成功");
            result.setCode(Result.SUCCESS);
            logger.info("操作成功");
        } catch (Exception e) {
            logger.info("保存失败", e);
            result.setCode(Result.FAIL);
            result.setMsg("操作失败");
        }
        return result;
    }
    /**
     * 批量删除
     *
     * @param accountIds
     *          要删除的id
     * @return JuiResult
     */
    @RequestMapping("/batchdelete")
    @ResponseBody
    public Result batchdelete(String accountIds) {
        Result result = new Result();
        try {
            if (!StringUtils.isEmpty(accountIds)) {
                for (String id : accountIds.split(",")) {
                    accountService.deleteUser(id, null);

                }
            }
            result.setMsg("删除成功");
            result.setCode(Result.SUCCESS);
            logger.info("删除成功");
        } catch (Exception e) {
            logger.info("删除失败", e);
            result.setCode(Result.FAIL);
            result.setMsg("删除失败");
        }
        return result;
    }
    /**
     * 修改
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(People ptPeople) {
        ptPeopleService.updateById(ptPeople);
        return SUCCESS_TIP;
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/detail/{ptPeopleId}")
    @ResponseBody
    public Object detail(@PathVariable("ptPeopleId") Integer ptPeopleId) {
        return ptPeopleService.selectById(ptPeopleId);
    }

    /**
     * 获取未分配家长的学生信息集合
     *
     * @param classUser
     *          班级用 户
     * @param peopleId
     *          用户id
     * @return 返回
     */
    @RequestMapping("/suggestStudentList")
    @ResponseBody
    public List<PtClassUser> suggestStudentList(PtClassUser classUser, String peopleId) {
        classUser.setType(PtClassUser.TYPE_STUDENT);
        classUser.setSchoolYear(MetaUtils.getSchoolYearProvider().getCurrentSchoolYear(classUser.getOrgId()));
        List<PtClassUser> findAll = classUserService.findStudents(classUser);

        return findAll;
    }

    /**
     * @param um
     *          搜索条件
     * @param people
     *          用户信息
     * @param response
     *          服务器响应
     * @param os
     *          输出流
     */
    @RequestMapping("exportPeople")
    public void exportPeople(UserSearchModel um, People people, HttpServletResponse response, OutputStream os) {

        try {
            String fileName = "";
            if (um.getUserType() == PtAccount.SYSTEM_USER) {
                fileName = "系统用户信息表";
            } else {
                fileName = "家长用户信息表";
            }
            if (um.getAreaId() != null) {
                String areaName = orgService.getAreaNameById(um.getAreaId());
                fileName = areaName + fileName;
            } else if (um.getOrgId() != null) {
                PtOrg org = orgService.selectById(people.getOrgId());
                if (org != null) {
                    String areaName = orgService.getAreaNameById(org.getAreaId());
                    fileName = areaName + org.getShortName() + fileName;
                }
            }
            response.setContentType("application/x-download");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO-8859-1") + ".xls");
        } catch (UnsupportedEncodingException e) {
            logger.error("导出用户失败", e);
        }
        Map<String, Object> params = new HashMap<>();
        List<Map<Integer, String>> dataList = new ArrayList<>();
        List<People> peopleList = null;
        if (um.getUserType() == PtAccount.SYSTEM_USER) {
            EntityWrapper<People> entityWrapper=new EntityWrapper<>();
            entityWrapper.eq("user_type",PtAccount.SYSTEM_USER);
            entityWrapper.eq("crt_dttm",false);
            peopleList = ptPeopleService.selectList(entityWrapper);
        } else {
            peopleList = ptPeopleService.exportPeoList(um);
        }
        People p = null;
        if (um.getUserType() == PtAccount.SYSTEM_USER) {
            for (int i = 0; i < peopleList.size(); i++) {
                Map<Integer, String> dataMap = new HashMap<>();
                p = peopleList.get(i);
                String userRoleStr = accountService.exportUserRole(p.getId());
                dataMap.put(0, accountService.selectById(p.getId()).getAccount());
                dataMap.put(1, p.getName());
                dataMap.put(2, SysRole.forCname(p.getUserType()));
                dataMap.put(3, userRoleStr);
                dataMap.put(4, GBSex.forCname(p.getSex()));
                dataMap.put(5, ConfigUtils.readConfig(MetaKeys.PF_BACK_UC_PASSWORD_KEY, "000000"));
                dataMap.put(6, p.getEnable() == true ? "否" : "是");
                dataList.add(dataMap);
            }
        } else {
            for (int i = 0; i < peopleList.size(); i++) {
                Map<Integer, String> dataMap = new HashMap<>();
                p = peopleList.get(i);
                String userRoleStr = accountService.exportUserRole(p.getId());
                dataMap.put(0, p.getAccount());
                dataMap.put(1, p.getName());
                dataMap.put(2, SysRole.forCname(p.getUserType()));
                dataMap.put(3, userRoleStr);
                dataMap.put(4, GBSex.forCname(p.getSex()));
                dataMap.put(5, ConfigUtils.readConfig(MetaKeys.PF_BACK_UC_PASSWORD_KEY, "000000"));
                dataMap.put(6, p.getEnable() == true ? "否" : "是");
                dataMap.put(7, p.getFlago());
                dataList.add(dataMap);
            }
        }
        params.put("data", dataList);
        params.put("userType", um.getUserType());
        StringBuilder resultMsg = null;

        batchExportUserService.exportData(os, params, resultMsg, null);
    }

}
